package net.jonbuck.tassoo.handler;

import net.jonbuck.tassoo.persistence.dao.TassooDao;
import net.jonbuck.tassoo.persistence.dao.TassooDaoImpl;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.preferences.IPreferencesService;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;

/**
 * 
 * 
 * @since 1.0.0
 */
public class QuitHandler extends AbstractHandler implements IHandler {

	private IPreferencesService preferenceService;

	private TassooDao tassooDao = TassooDaoImpl.getInstance();

	/**
	 * 
	 */
	public Object execute(ExecutionEvent event) throws ExecutionException {
		preferenceService = Platform.getPreferencesService();
		if (preferenceService.getBoolean("net.jonbuck.tassoo", "prompt.to.save.task.store.on.exit", false, null)) {
			if (MessageDialog.openQuestion(Display.getDefault().getActiveShell(), "Save Task Store",
					"Do you wish to save the current Task Store before quitting?")) {
				tassooDao.saveTaskStore();
			}
		}

		IWorkbenchWindow activeWorkbenchWindow = HandlerUtil.getActiveWorkbenchWindow(event);
		if (activeWorkbenchWindow == null) {
			// action has been disposed
			return null;
		}

		activeWorkbenchWindow.getWorkbench().close();
		return null;
	}

}
